import React, { PureComponent } from 'react'
import { message, Popconfirm, Tabs } from 'antd'
import { connect, history } from '@umijs/max'
import {
 BreadcrumbBar, InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import { getHashParameterByName } from '@/utils/helper'
import styles from './index.less'

const menus = [{ name: 'API管理' }, { name: '我的申请' }]
const tabArr = [{ name: '已授权', disabled: false, key: '1' }, { name: '待审批', disabled: false, key: '0' }, { name: '已撤回', disabled: false, key: '4' }, { name: '已取消', disabled: false, key: '2' }, { name: '未通过', disabled: false, key: '3' }]

const { TabPane } = Tabs
const { OperateItem } = ProTableOperate

class MyApply extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      activeKey: '1',
      columns1: [
        {
          title: 'API名称',
          dataIndex: 'apiName',
          width: '20%',
          key: 'apiName',
          // ellipsis: true,
          render: (apiName) => (apiName || '-'),
        },
        {
          title: 'API描述',
          dataIndex: 'apiDesc',
          width: '25%',
          key: 'apiDesc',
          // ellipsis: true,
          render: (apiDesc) => (apiDesc || '-'),
        },
        {
          title: '状态',
          dataIndex: 'approveStatus',
          width: '20%',
          key: 'approveStatus',
          render: (approveStatus) => (
            <>
              {
                approveStatus === 0 && (
                  <><i className="iconfont icon-daiban hu-blue" /> 待审批</>
                )
              }
              {
                approveStatus === 1 && (
                  <><i className="iconfont icon-chenggong hu-green" /> 已授权</>
                )
              }
              {
                approveStatus === 2 && (
                  <><i className="iconfont icon-caogao hu-gray" /> 已取消</>
                )
              }
              {
                approveStatus === 3 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 未通过</>
                )
              }
              {
                approveStatus === 4 && (
                  <><i className="iconfont icon-chehui hu-orange" /> 已撤回</>
                )
              }
            </>
          ),
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: '20%',
          key: 'applyTime',
          render: (applyTime) => (applyTime || '-'),
        },
        {
          title: '操作',
          width: '20%',
          render: (record) => {
            const { approveStatus, id } = record
            return (
              <ProTableOptions>
                {
                (approveStatus === 0 || null) && <span onClick={() => { this.queryCancelApiApproveById(id) }}>撤回</span>
              }
                {
                (approveStatus === 2 || approveStatus === 4 || null) && (<span onClick={() => { this.queryApplyApiById(id) }}>再次申请</span>)
              }
                {
                (approveStatus === 3 || null) && (<span onClick={() => { this.queryApplyApiById(id) }}>重新申请</span>)
              }
                {
                (approveStatus === 3 || null) && (
                  <Popconfirm
                    title="你确定要删除吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => this.queryRemoveDataApiById(id)}
                  >
                    <span key="delete">
                      删除
                    </span>
                  </Popconfirm>
                )
              }
              </ProTableOptions>
            )
          },
        },
      ],
      columns2: [
        {
          title: 'API名称',
          dataIndex: 'apiName',
          width: '15%',
          key: 'apiName',
          render: (apiName) => (apiName || '-'),
          // ellipsis: true,
        },
        {
          title: 'API描述',
          dataIndex: 'apiDesc',
          width: '20%',
          key: 'apiDesc',
          // ellipsis: true,
          render: (apiDesc) => (apiDesc || '-'),
        },
        {
          title: '累计调用次数',
          dataIndex: 'totalCount',
          width: '14%',
          key: 'totalCount',
          // render: (totalCount) => (totalCount || '-'),
        },
        {
          title: '状态',
          dataIndex: 'approveStatus',
          width: '12%',
          key: 'approveStatus',
          render: (approveStatus) => (
            <>
              {
                approveStatus === 0 && (
                  <><i className="iconfont icon-daiban hu-blue" /> 待审批</>
                )
              }
              {
                approveStatus === 1 && (
                  <><i className="iconfont icon-chenggong hu-green" /> 已授权</>
                )
              }
              {
                approveStatus === 2 && (
                  <><i className="iconfont icon-caogao hu-gray" /> 已取消</>
                )
              }
              {
                approveStatus === 3 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 未通过</>
                )
              }
              {
                approveStatus === 4 && (
                  <><i className="iconfont icon-chehui hu-orange" /> 已撤回</>
                )
              }
            </>
          ),
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: '20%',
          key: 'applyTime',
          render: (applyTime) => (applyTime || '-'),
        },
        {
          title: '操作',
          // width: '20%',
          render: (record) => {
            const { apiType, apiId } = record
            return (
              <ProTableOptions>
                <span onClick={() => {
                  (apiType === 0 || apiType === 1) && history.push({ pathname: `/data-service/api-manage/produce-api-detail?id=${apiId}&type=apply` })
                  apiType === 2 && history.push({ pathname: `/data-service/api-manage/register-api-detail?id=${apiId}&type=apply` })
                  apiType === 3 && history.push({ pathname: `/data-service/api-manage/index-api-detail?id=${apiId}&type=apply` })
                }}
                >查看
                </span>
              </ProTableOptions>
            )
          },
        },
      ],
      query: {
        approveStatus: getHashParameterByName('activeKey') || '1',
      },
      apiName: '',
      loading: false,
      forceUpdate: 0,
    }
    this.tableRef = React.createRef()
  }

  componentDidMount() {
    const activeKey = getHashParameterByName('activeKey') || ''
    if (activeKey) {
      this.setState({
        activeKey,
      })
    }
  }

  // 删除
  queryRemoveDataApiById = (id) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'myApply/queryRemoveDataApiById',
      params: { id },
      cb: (res) => {
        this.setState({ loading: false })
        const { msg, status } = res
        if (status === 200) {
          this.forceUpdateFn()
          message.success('操作成功')
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  queryCancelApiApproveById = (id) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'myApply/queryCancelApiApproveById',
      params: {
        id,
      },
      cb: (res) => {
        this.setState({ loading: false })
        const { msg, status } = res
        if (status === 200) {
          this.forceUpdateFn()
          message.success('操作成功')
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 申请使用
  queryApplyApiById = (id) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'myApply/queryApplyApiById',
      params: {
        id,
      },
      cb: (res) => {
        this.setState({ loading: false })
        const { msg, status } = res
        if (status === 200) {
          this.forceUpdateFn()
          message.success('操作成功')
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  onTabsChange = (activeKey) => {
    this.setState({
      activeKey,
      apiName: '',
    }, () => {
      this.fetchData()
    })
  }

  fetchData = () => {
    const { activeKey, apiName, query } = this.state
    this.tableRef?.current?.resetPageNum()
    const tempQuery = {}
    tempQuery.apiName = apiName
    tempQuery.approveStatus = activeKey
    this.setState({
      query: {
        ...query,
        ...tempQuery,
      },
    })
  }

  forceUpdateFn = () => {
    this.setState((prevState) => ({
      forceUpdate: prevState.forceUpdate + 1,
    }))
  }

  render() {
    const {
      activeKey, columns1, columns2, query, apiName, loading, forceUpdate,
    } = this.state
    return (
      <div className={styles.my_apply}>
        <BreadcrumbBar menu={menus} />
        <Tabs
          destroyInactiveTabPane
          defaultActiveKey="1"
          type="card"
          onChange={this.onTabsChange}
          activeKey={activeKey}
          className={styles.page_content_tabs}
        >
          {
            tabArr.map((item, index) => (
              <TabPane disabled={item.disabled} tab={item.name} key={item.key} />
            ))
          }
        </Tabs>
        <div className={styles.container}>
          <ProTableOperate>
            <OperateItem align="left">
              <InputSearch
                placeholder="请输入API名称进行搜索"
                value={apiName}
                onChange={(e) => {
                  this.setState({
                    apiName: e.target.value,
                  })
                }}
                onSearch={this.fetchData}
              />
            </OperateItem>
          </ProTableOperate>
          <ProTable
            ref={this.tableRef}
            key={forceUpdate}
            loading={loading}
            url="/api/v1/dataApiMyApply/getMyApplyApiPage"
            query={query}
            rowKey="id"
            columns={activeKey === '1' ? columns2 : columns1}
          />
        </div>
      </div>
    )
  }
}

export default connect(({ myApply }) => ({ ...myApply }))(MyApply)
